package cn.edu.thu.laud.auth;

import java.nio.ByteBuffer;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;

import org.apache.cassandra.db.marshal.UTF8Type;


public enum AuthorityGroup {

	DBADMIN,
	DBDESIGN,
	FORBIDDEN,
	SYSTEM;

	private static final String DB_ADMIN_STRING="dbAdmin" ;
	private static final String DB_DESIGN_STRING="dbDesign" ;
	//	private static final String NORMAL_STRING="normal" ;
	private static final String FORBIDDEN_STRING="forbidden" ;
	private static final String SYSTEM_STRING="system" ;

	public static final ByteBuffer DB_ADMIN_BYTE_BUFFER=UTF8Type.instance.decompose(DB_ADMIN_STRING);
	public static final ByteBuffer DB_DESIGN_BYTE_BUFFER=UTF8Type.instance.decompose(DB_DESIGN_STRING);
	//	public static final ByteBuffer NORMAL_BYTE_BUFFER=UTF8Type.instance.decompose(NORMAL_STRING);
	public static final ByteBuffer FORBIDDEN_BYTE_BUFFER=UTF8Type.instance.decompose(FORBIDDEN_STRING);
	public static final ByteBuffer SYSTEM_BYTE_BUFFER=UTF8Type.instance.decompose(SYSTEM_STRING);

	public String toString(){
		switch (this) {
		case DBADMIN:
			return DB_ADMIN_STRING;
		case DBDESIGN:
			return DB_DESIGN_STRING;
			//		case NORMAL:
			//			return NORMAL_STRING;
		case FORBIDDEN:
			return FORBIDDEN_STRING;
		case SYSTEM:
			return SYSTEM_STRING;
		default:
			return null;
		}
	}
	public int getValue(){
		switch (this) {
		case DBADMIN:
			return 64;
		case DBDESIGN:
			return 32;
		case FORBIDDEN:
			return 1;
		case SYSTEM:
			return 128;
		default:
			return 0;
		}
	}
	public AuthorityGroup less(AuthorityGroup group){
		switch (this) {

		case DBADMIN:
			return DBDESIGN;
		case DBDESIGN:
			return FORBIDDEN;
		case FORBIDDEN:
			return null;
		case SYSTEM:
			return DBADMIN;
		default:
			return null;
		}
	}
	public AuthorityGroup getValue(int value){
		switch (value) {
		case 64:
			return SYSTEM;
		case 32:
			return DBDESIGN;
		case 128:
			return SYSTEM;
		case 1:
			return FORBIDDEN;
		default:
			return null;
		}
	}
	
	public static EnumSet<AuthorityGroup> split(int value){
		
		AuthorityGroup levelGroup=SYSTEM;
		int level=SYSTEM.getValue();
		
		Set<AuthorityGroup> tmpGroups=new HashSet<AuthorityGroup>();
		
		while(levelGroup!=null&&value!=0){
			level=levelGroup.getValue();
			if(value/level==1)
				tmpGroups.add(levelGroup);
			value%=level;
			levelGroup=levelGroup.less(levelGroup);
		}
		return EnumSet.copyOf(tmpGroups);
	}
	public static void main(String[] agadfasd){
		
		for(AuthorityGroup group:split(225)){
			System.out.println(group.toString());
		}
	}
}
